import React, { useState } from 'react';
import { Form, Input, Button, Card, message } from 'antd';
import { LockOutlined, MailOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { setToken, setUser } from '../../utils';
import authService from '../../services/authService';
import './Login.scss';

const Login = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  // 登录处理 - 支持管理员和普通用户
  const handleLogin = async (values) => {
    try {
      setLoading(true);
      
      // 先尝试管理员登录
      let response = await authService.adminLogin(values);
      
      // 如果管理员登录失败，尝试普通用户登录
      if (!response.success) {
        console.log('管理员登录失败，尝试普通用户登录...');
        response = await authService.login(values);
      }
      
      if (response.success) {
        setToken(response.data.token);
        setUser(response.data.user);
        message.success('登录成功');
        navigate('/', { replace: true });
      } else {
        message.error(response.message || '登录失败');
      }
    } catch (error) {
      console.error('登录错误:', error);
      message.error('登录失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };



  return (
    <div className="login-container">
      <div className="login-background">
        <div className="background-overlay"></div>
      </div>
      
      <div className="login-content">
        <Card className="login-card">
          <div className="login-header">
            <h1>大数据与人工智能学院作品发布系统</h1>
          </div>

          <Form
            name="adminLogin"
            onFinish={handleLogin}
            autoComplete="off"
            size="large"
          >
            <Form.Item
              name="email"
              rules={[
                { required: true, message: '请输入用户名或邮箱' },
                { min: 3, message: '用户名至少3位' }
              ]}
            >
              <Input
                prefix={<MailOutlined />}
                placeholder="用户名或邮箱"
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[
                { required: true, message: '请输入密码' },
                { min: 6, message: '密码至少6位' }
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="密码"
              />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
                block
              >
                登录
              </Button>
            </Form.Item>
          </Form>

          <div className="login-tips">
            <p style={{ textAlign: 'center', color: '#666', fontSize: '14px' }}>
              @2025 大数据与人工智能平台
            </p>
          </div>
        </Card>
      </div>
    </div>
  );
};

export default Login;